/**
 * Project Name:jh
 * File Name:DBUtils.java
 * Package Name:com.jh.utils
 * Date:下午8:58:56
 * Copyright (c) 2021, LZ All Rights Reserved.
 *
*/

package com.jh.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Description: 工具类，初始化数据库连接池，创建核心工具类的方法<br/>
 * Date: 下午8:58:56 <br/>
 * 
 * @author lz E-mail:withitren@outlook.com
 * @version
 * @see
 */
public class DBUtils {

    static final Logger logger = LoggerFactory.getLogger(DBUtils.class);

    /*初始化连接池*/
    private static DataSource dataSource = null;

    /*加载c3p0配置文件，运行一次*/
    static {
        /*自动加载c3p0-config.xml,名称固定*/
        dataSource = new ComboPooledDataSource();
    }

    /*获取QueryRunner对象*/
    public static QueryRunner getQueryRunner() {
        /*创建QueryRunner对象，并传入连接池对象 ,会自动从数据源(DataSource)获取连接，不用去手动关闭连接*/
        return new QueryRunner(dataSource);
    }

    /*获取数据库连接*/
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("SQLException:", e);
        }
        return null;
    }

    /*实现增删改*/
    public static boolean addDelUpdate(String sql, Object[] arr) throws Exception {
        QueryRunner qr = getQueryRunner();
        int rst = qr.update(sql, arr);
        if (rst > 0) {
            logger.debug("addDelUpdate ok!");
            return true;
        } else {
            logger.debug("addDelUpdate failed!");
            return false;
        }

    }
}
